﻿using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Edu.Http.Extensions;
using Edu.Http.Proxy;
using Infrastructure.Config.Core.External;
using Infrastructure.ExternalService.Core.BasicData;
using Infrastructure.ExternalService.Core.Requests;
using Infrastructure.ExternalService.Core.Responses;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Volo.Abp.Application.Dtos;
using Volo.Abp.DependencyInjection;

namespace Infrastructure.ExternalService.Core.Imp.BasicData
{
    public class BasicDataClient : BaseHttpClient, IBasicDataClient, ITransientDependency
    {
        private readonly OrderCenterApiOptions _orderingOptions;
        private readonly string formUrlencoded = "application/x-www-form-urlencoded";

        public BasicDataClient(IOptions<OrderCenterApiOptions> options,
            HttpClient client, ILoggerFactory loggerFactory)
            : base(client, loggerFactory, options.Value.BasicDataOptions.EndPoint)
        {
            _orderingOptions = options.Value ?? throw new HttpProxyException($"{nameof(BasicDataClient)}配置获取失败");
            loggerFactory.CreateLogger<BasicDataClient>();
        }

        /// <summary>
        /// 设置BaseHttpClient的BaseAddress：该值默认是从构造函数传入的，但重写该方法可以改变该值
        /// </summary>
        /// <returns></returns>
        protected override string SetHttpClientBaseAddress()
        {
            return null;
        }

        #region 接口实现方法

        /// <summary>
        /// 添加订单时，根据前端提供的班级Ids获取班级信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<ClassResponse>> GetClassesAsync(GetClassesRequest request)
        {
            if (string.IsNullOrEmpty(request.ClassIds))
            {
                return (new List<ClassResponse>());
            }

            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<GenericPagedListResponse<ClassResponse>>>(url: _orderingOptions.BasicDataOptions.GetClasses, jsonStr: formStr, formUrlencoded, headers: null);

            if (response.Success && response.Data != null && response.Data.Count >= 0)
            {
                return response.Data.Data;
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        /// <summary>
        /// 获取手机号归属地
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public async Task<MobileResponse> GetMobileAsync(GetMobileAttributeRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<MobileResponse>>(url: _orderingOptions.BasicDataOptions.GetMobileAttribute, jsonStr: formStr, formUrlencoded, headers: null);

            if (response.Success && response.Data != null)
            {
                return response.Data;
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        /// <summary>
        /// 通过源班级ID获取班级信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<SingleClassResponse> GetClassBySourceIdAsync(GetSingleClassRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<SingleClassResponse>>(url: _orderingOptions.BasicDataOptions.GetSingleClass, jsonStr: formStr, formUrlencoded, headers: null);

            if (response != null && response.Success)
            {
                return response.Data;
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<int> GetClassPeriodAsync(GetClassPeriodRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<Dictionary<string, int?>>>(url: _orderingOptions.BasicDataOptions.ClassPeriod, jsonStr: formStr, formUrlencoded, headers: null);

            if (response != null && response.Success)
            {
                return response.Data["data"].GetValueOrDefault();
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<bool> VerifyBuyAndGiveClassRelationAsync(VerifyBuyAndGiveClassRelationRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<SingleValue<bool>>>(url: _orderingOptions.BasicDataOptions.VerifyBuyAndGiveClassRelation, jsonStr: formStr, formUrlencoded, headers: null);

            if (response != null && response.Success)
            {
                return response.Data.Result;
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<EmployeeResponse> GetEmployeeInfoAsync(GetEmployeeRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<EmployeeResponse>>(url: _orderingOptions.BasicDataOptions.GetEmployeeInfo, jsonStr: formStr, formUrlencoded, headers: null);

            if (response != null && response.Success && response.Data != null)
            {
                return response.Data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException("员工信息不存在");
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<BasicSchoolResponse> GetSchoolIdsAsync(GetDBSchoolRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<BasicSchoolResponse>>(url: _orderingOptions.BasicDataOptions.GetDptSchool, jsonStr: formStr, formUrlencoded, headers: null);

            if (response != null && response.Success && response.Data != null)
            {
                return response.Data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException("商户信息不存在");
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<Dictionary<string, string>> GetAgreementSnapshotAsync(CreateAgreementSnapshotRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<Dictionary<string, string>>>(url: _orderingOptions.BasicDataOptions.CreateAgreementSnapshot, jsonStr: formStr, formUrlencoded, headers: null);

            if (response != null && response.Success && response.Data != null)
            {
                return response.Data;
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<List<CourseInfo>> SearchCourseAsync(SearchClassesRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response =
                await GetAsync<WrapResponse<GenericPagedListResponse<CourseInfo>>>(
                    _orderingOptions.BasicDataOptions.Search + "?" + formStr);
            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data.Data;
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<List<DptSchoolInfoResponse>> GetDptSchoolNamesAsync(GetDptSchoolNamesRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<GenericPagedListResponse<DptSchoolInfoResponse>>>(url: _orderingOptions.BasicDataOptions.GetDptSchoolNames, jsonStr: formStr, formUrlencoded, headers: null);

            if (response != null && response.Success && response.Data != null)
            {
                return response.Data.Data;
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<List<ClasssInfoResponse>> GetClassInfoAsync(GetClassesRequest request)
        {
            if (string.IsNullOrEmpty(request.ClassIds))
            {
                return (new List<ClasssInfoResponse>());
            }

            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<GenericPagedListResponse<ClasssInfoResponse>>>(url: _orderingOptions.BasicDataOptions.GetClassInfo, jsonStr: formStr, formUrlencoded, headers: null);

            if (response != null && response.Success && response.Data != null && response.Data.Count >= 0)
            {
                return response.Data.Data;
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        #endregion
    }
}